package cn.ydt.ydt.community.common.utils;


import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 得到距离
 * @author Administrator
 */
public class DistanceUtils {


    /**
     * 高德地图API接口
     */
    private static final String GD_URL="https://restapi.amap.com/v5/direction/driving";
    /**
     * 高德地图key
     */
    private static final String GD_KEY="f2e26c3438c7f8b6f711deb3d8af1d93";



    private DistanceUtils() {
        throw new AssertionError("不能产生实例");
    }


    /**
     *
     * @param origin 起始点的经度纬度用","分隔
     * @param destination 目标点点的经度纬度用","分隔
     * @return
     */
    public static JSONObject getDistance(String origin , String  destination) {
        Map<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("key"  , GD_KEY);
        paramsMap.put("origin" , origin);
        paramsMap.put("destination" , destination);
        String params = toQueryString(paramsMap);
        JSONObject res = null;
        JSONObject obj = null;
        //发送请求
        res = HttpUtils.doGet(GD_URL, paramsMap);
        //转换为josn字符串
        obj = JSONObject.parseObject(res.toJSONString());
        return obj;
    }

    public static double getLineDistance(double lat1, double lng1, double lat2, double lng2){

            double radLat1 = lat1 * Math.PI / 180.0;
            double radLat2 = lat2 * Math.PI / 180.0;
            double lng_1 = lng1 * Math.PI / 180.0;
            double lng_2 = lng2 * Math.PI / 180.0;
           // 两点纬度差
            double a = radLat1 - radLat2;
           // 两点的经度差
            double b = lng_1 - lng_2;
            double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1)
                    * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378.137;
            return s;
    }


    // 对Map内所有value作utf8编码，拼接返回结果
    private static String toQueryString(Map<?, ?> data) {
        StringBuffer queryString = null;
        try {
            queryString = new StringBuffer();
            for (Map.Entry<?, ?> pair : data.entrySet()) {
                queryString.append(pair.getKey() + "=");
                queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&");
            }
            if (queryString.length() > 0) {
                queryString.deleteCharAt(queryString.length() - 1);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return queryString.toString();
    }



}
